package com.infovane.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;


import com.infovane.base.BaseAction;
import com.infovane.model.TArticle;
import com.infovane.model.TArticleFile;
import com.infovane.model.TTopic;
import com.infovane.model.TUser;
import com.infovane.service.AdminService;
import com.infovane.service.ArticleFileService;
import com.infovane.service.ArticleService;
import com.infovane.service.TopicService;
import com.infovane.utils.CheckFileType;
import com.infovane.utils.SystemConstant;


public class AdminAction extends BaseAction{
	
	private AdminService adminService;
	
	
	public AdminService getAdminService() {
		return adminService;
	}


	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}
	
	private ArticleFileService articleFileService;
	
	
	private ArticleService articleService;
	
	private TopicService topicService;
	
	
	
	
	
	//上传文件域对象
	private File[] uploads;
	//上传文件名
	private String[] uploadFileNames;
	//上传文件类型
	private String[] uploadContentTypes;
	//上传文件保存路径（通过sturts配置文件注入）
	private String savePath;
	//上传图片保存路径（通过struts配置文件注入）
	private String savePicture;
	
    public File[] getUpload() {
		
		return this.uploads;
	} 
	public void setUpload(File[] upload) {
		this.uploads = upload; 
	} 
	 
	public String[] getUploadFileName() { 
		return this.uploadFileNames;
	} 
	public void setUploadFileName(String[] uploadFileName) { 
		this.uploadFileNames = uploadFileName; 
	} 
	 
	public String[] getUploadContentType() { 
		return this.uploadContentTypes; 
	} 
	public void setUploadContentType(String[] uploadContentType) { 
		this.uploadContentTypes = uploadContentType; 
	}
	
	public String getSavePath() {
		return savePath;
	}


	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
	public String getSavePicture() {
		return savePicture;
	}


	public void setSavePicture(String savePicture) {
		this.savePicture = savePicture;
	}
	
	private File myFile;//文件对象
    private String fileName;//文件名
    private String imageFileName;//文件为图片时，新建的图片名
    
    public void setMyFileFileName(String fileName) {
        this.fileName = fileName;
   } 
       
    public void setMyFile(File myFile) {
        this.myFile = myFile;
   } 
   
    public String getImageFileName() {
        return imageFileName;
   }
    
	/**
	 * 把源文件对象复制成目标文件对象
	 */
	private static void copy(File src,File dst){
		InputStream in=null;
		OutputStream out=null;
		try{
		in=new BufferedInputStream(new FileInputStream(src),SystemConstant.BUFFER_SIZE); 
		out=new BufferedOutputStream(new FileOutputStream(dst),SystemConstant.BUFFER_SIZE);
		byte[] buffer= new byte[SystemConstant.BUFFER_SIZE];
		int len=0;
		while((len=in.read(buffer))>0){
			out.write(buffer, 0, len);
		}
		}catch(Exception e){
			logger.info("upload failed!",e);
		}finally{
			if(in!=null){
				try{
				in.close();
				in=null;
				}catch(IOException e){
					logger.info("in close failed!",e);
				}
			}
			if(out!=null){
				try{
				out.close();
				out=null;
				}catch(IOException e){
					logger.info("out close failed!",e);
				}
			}
		}
	}
	
	/**
	 * 管理员登录
	 * */
	public String login(){
		String username=httpServletRequest.getParameter("username");
		String password=httpServletRequest.getParameter("password");
		if(username==null||username.equals("")){
			String warn="帐号不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else if(password==null||password.equals("")){
			String warn="密码不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else{
			TUser user=null;
			user=this.adminService.checkLogin(username, password);
			if(user!=null&&user.getUserIfAdmin()==1){
				session.put("ADMIN", user);//管理员对象
				session.put("USERNAME",user.getUserName());//管理员名字
				session.put("IFADMIN",user.getUserIfAdmin() );//判断是否为管理员
				session.put("LIMIT",user.getUserAdminLimit());//管理员权限
				httpServletRequest.getSession().setMaxInactiveInterval(900);//session失效时间
				return SUCCESS;
			}else{
				String warn="帐号或密码错误!";
				httpServletRequest.setAttribute("WARN", warn);
			}
			
		}
		return ERROR;
	}
	
	/**
	 * 管理员退出登陆
	 * */
	public String logout(){
		httpServletRequest.getSession().invalidate();
		return SUCCESS;
	}
	
	/**
	 * 管理员创建新文章
	 * */
	public String adminCreateArticle(){
		int grade=0,consult=1,authority=1;
		Long click=0L;
		try{
			click=Long.parseLong(httpServletRequest.getParameter("click"));//文章点击数,默认为0;
			grade=Integer.parseInt(httpServletRequest.getParameter("grade"));//文章等级，默认为0(普通);
			consult=Integer.parseInt(httpServletRequest.getParameter("consult"));//文章是否审核，默认为1（已审核）;
			authority=Integer.parseInt(httpServletRequest.getParameter("authority"));//文章是否为官网发布，默认为1（是）;
		}catch(NullPointerException e){
			click=0L;
			grade=0;
			consult=1;
			authority=1;
		}
		String authorname,title,color,keywords,source,typename,stylename,styleimage,summary,content;
		try{
		authorname=(String)httpServletRequest.getSession().getAttribute("USERNAME");
		title=(String)httpServletRequest.getParameter("title");//文章标题
		color=(String)httpServletRequest.getParameter("color");//文章标题颜色
		keywords=(String)httpServletRequest.getParameter("keywords");//文章关键字
		source=(String)httpServletRequest.getParameter("source");//文章来源
		typename=(String)httpServletRequest.getParameter("typename");//文章大类别
		stylename=(String)httpServletRequest.getParameter("stylename");//文章小类别
		styleimage=(String)httpServletRequest.getParameter("articleimg");//文章所属标示
		summary=(String)httpServletRequest.getParameter("summary");//文章概要
		content=(String)httpServletRequest.getParameter("content");//文章内容
		}catch(NullPointerException e){
			String warn="输入栏不能为空！";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}catch(Exception e){
			String warn="您输入的数据有误！";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}
		if(summary==null||summary.equals("")){
			String warn="文章概要不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else if(content==null||content.equals("")){
			String warn="文章内容不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else{
			File[] srcFiles=this.getUpload();
			String aFileIndex="not";
			if(srcFiles!=null){
				Long times=new Date().getTime();
				aFileIndex="a"+times;
				String newFileName,fileType,dstPath,newFileUrl;
				for(int i=0;i<srcFiles.length;i++){
					newFileName=new Date().getTime()+i+CheckFileType.getExtention(this.getUploadFileName()[i]);
					fileType=this.getUploadContentType()[i];
					//判断文件类型
					if(CheckFileType.isPic(this.getUploadFileName()[i])){
						 // 根据服务器的文件保存地址和文件名创建目录文件全路径
						dstPath=ServletActionContext.getServletContext().getRealPath(this.savePicture)+"/"+newFileName;
						newFileUrl=this.savePicture+"/"+newFileName;
					}else{
						// 根据服务器的文件保存地址和文件名创建目录文件全路径
						dstPath=ServletActionContext.getServletContext().getRealPath(this.savePath)+"/"+newFileName;
						newFileUrl=this.savePath+"/"+newFileName;
					}
					TArticleFile aFile=new TArticleFile();
					aFile.setArticleFileUrl(newFileUrl);
					aFile.setArticleFileDown(dstPath);
					aFile.setArticleFileIndex(aFileIndex);
					aFile.setArticleFileName(newFileName);
					aFile.setArticleFileType(fileType);
					File desFile=new File(dstPath);
					copy(srcFiles[i],desFile);
					this.articleFileService.add(aFile);
					
				}
				
			}
			TArticle article=new TArticle();
			article.setArticleClick(click);
			article.setArticleContent(content);
			article.setArticleCreateTime(new Date());
			article.setArticleFileIndex(aFileIndex);
			article.setArticleGrade(grade);
			article.setArticleIfAuthority(authority);
			article.setArticleIfConsult(consult);
			article.setArticleKeywords(keywords);
			article.setArticleSource(source);
			article.setArticleStyleImage(styleimage);
			article.setArticleStyleName(stylename);
			article.setArticleSummary(summary);
			article.setArticleTitle(title);
			article.setArticleTitleColor(color);
			article.setArticleTypeName(typename);
			article.setAuthorName(authorname);
			article.setArticleSumComment(0);
			boolean sign=this.articleService.add(article);
			if(!sign){
				String warn="文章保存出错！";
				httpServletRequest.setAttribute("WARN",warn);
				return ERROR;
			}
		}
		return SUCCESS;
		
	}
	
	/**
	 * 管理员发表专题
	 * */
	public String adminTopicIssue(){
		int status=0;
		long click=0L;
		try{
			status=Integer.parseInt(httpServletRequest.getParameter("status"));
		}catch(NullPointerException e){
			status=0;
		}
		String title,keywords,source,author,typename,stylename,topicimg,describe,summary,content;
		try{
			title=(String)httpServletRequest.getParameter("title");
			keywords=(String)httpServletRequest.getParameter("keywords");
			source=(String)httpServletRequest.getParameter("source");
			author=(String)httpServletRequest.getSession().getAttribute("USERNAME");
			typename=(String)httpServletRequest.getParameter("typename");
			stylename=(String)httpServletRequest.getParameter("stylename");
			topicimg=(String)httpServletRequest.getParameter("topicimg");
			describe=(String)httpServletRequest.getParameter("describe");
			summary=(String)httpServletRequest.getParameter("summary");
			content=(String)httpServletRequest.getParameter("content");
		}catch(NullPointerException e){
			String warn="输入栏不能为空！";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}catch(Exception e){
			String warn="您输入的数据有误！";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}
		if(describe==null||describe.equals("")){
			String warn="专题描述不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else if(summary==null||summary.equals("")){
			String warn="专题概要不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else if(content==null||content.equals("")){
			String warn="专题内容不能为空!";
			httpServletRequest.setAttribute("WARN",warn);
			return ERROR;
		}else{
			if(myFile!=null){
				if(!CheckFileType.isPic(fileName)){
					String warn="上传文件只能为图片!";
					httpServletRequest.setAttribute("WARN",warn);
					return ERROR;
				}else{
					imageFileName=new Date().getTime()+"t"+CheckFileType.getExtention(fileName);
					File imageFile=new File(ServletActionContext.getServletContext().getRealPath(this.savePicture)+"/"+imageFileName);
					String imagePath=this.savePicture+"/"+imageFileName;
					copy(myFile,imageFile);
					TTopic topic=new TTopic();
					topic.setArticleKeywords(keywords);
					topic.setArticleStyleImage(topicimg);
					topic.setArticleStyleName(stylename);
					topic.setArticleTypeName(typename);
					topic.setAuthorName(author);
					topic.setToipcClick(click);
					topic.setTopicContent(content);
					topic.setTopicCreateTime(new Date());
					topic.setTopicDescribe(describe);
					topic.setTopicFileIndex("not");
					topic.setTopicImageName(imageFileName);
					topic.setTopicImageUrl(imagePath);
					topic.setTopicKeywords(keywords);
					topic.setTopicSource(source);
					topic.setTopicStatus(status);
					topic.setTopicSummary(summary);
					topic.setTopicTitle(title);
					boolean sign=this.topicService.add(topic);
					if(!sign){
						String warn="添加专题出错！";
						httpServletRequest.setAttribute("WARN",warn);
						return ERROR;
					}
				}
			}
		}
		return SUCCESS;
	}
	
	


	public ArticleFileService getArticleFileService() {
		return articleFileService;
	}


	public void setArticleFileService(ArticleFileService articleFileService) {
		this.articleFileService = articleFileService;
	}


	public ArticleService getArticleService() {
		return articleService;
	}


	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}


	public TopicService getTopicService() {
		return topicService;
	}


	public void setTopicService(TopicService topicService) {
		this.topicService = topicService;
	}





	

}
